#!/usr/bin/env python3
"""
修复Windows subprocess兼容性问题
"""

import re
from pathlib import Path

def fix_subprocess_issue():
    """修复video_splitter.py中的subprocess兼容性问题"""
    
    file_path = Path("app/services/video_splitter.py")
    
    if not file_path.exists():
        print(f"❌ 文件不存在: {file_path}")
        return
    
    # 读取文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 查找并替换asyncio subprocess部分
    old_pattern = r'            process = await asyncio\.create_subprocess_exec\(\r?\n                \*cmd,\r?\n                stdout=asyncio\.subprocess\.PIPE,\r?\n                stderr=asyncio\.subprocess\.PIPE\r?\n            \)\r?\n            \r?\n            stdout, stderr = await process\.communicate\(\)'
    
    new_code = '''            # 使用同步subprocess避免Windows兼容性问题
            import subprocess
            process = subprocess.run(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                timeout=300  # 5分钟超时
            )
            
            stdout, stderr = process.stdout, process.stderr'''
    
    # 执行替换
    new_content = re.sub(old_pattern, new_code, content)
    
    if new_content != content:
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        print(f"✅ 已修复 {file_path} 的subprocess兼容性问题")
    else:
        print(f"⚠️ 未找到需要修复的代码模式，尝试手动替换...")
        
        # 手动查找和替换
        lines = content.split('\n')
        for i, line in enumerate(lines):
            if 'await asyncio.create_subprocess_exec(' in line:
                print(f"找到asyncio subprocess位置: 第{i+1}行")
                # 替换这一段代码
                new_lines = lines[:i] + [
                    '            # 使用同步subprocess避免Windows兼容性问题',
                    '            import subprocess',
                    '            process = subprocess.run(',
                    '                cmd,',
                    '                stdout=subprocess.PIPE,',
                    '                stderr=subprocess.PIPE,',
                    '                timeout=300  # 5分钟超时',
                    '            )',
                    '            ',
                    '            stdout, stderr = process.stdout, process.stderr'
                ]
                
                # 跳过原来的代码行
                j = i + 1
                while j < len(lines) and ('stdout, stderr = await process.communicate()' not in lines[j]):
                    j += 1
                if j < len(lines):
                    j += 1  # 跳过communicate行
                
                new_lines.extend(lines[j:])
                
                # 写回文件
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write('\n'.join(new_lines))
                print(f"✅ 已手动修复 {file_path} 的subprocess兼容性问题")
                return
        
        print(f"❌ 未找到需要修复的代码")

if __name__ == "__main__":
    fix_subprocess_issue()